package com.example.mqexamples.custom.mq;

import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Description TODO
 * @Author benjamin
 * @Date 2020/1/21 9:54
 * @Version
 */
public class BrokerServer implements Runnable {

    public static int SERVER_PORT = 9999;

    private final Socket socket;

    public BrokerServer(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter out = new PrintWriter(socket.getOutputStream());
        ) {

            while (true) {


                String str = in.readLine();

                if (StringUtils.isEmpty(str)) {
                    continue;
                }

                System.out.println("接收到原始数据： " + str);

                if (str.equals("CONSUME")) {
                    String msg = Broker.consume();
                    out.println(msg);
                    out.flush();
                } else {
                    Broker.produce(str);
                }

            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        try {
            ServerSocket serverSocket = new ServerSocket(SERVER_PORT);

            System.out.println("serversocket 启动");

            while (true) {

                System.out.println("serversocket 阻塞等待");

                // 阻塞式等待请求
                BrokerServer runnable = new BrokerServer(serverSocket.accept());

                new Thread(runnable).start();

            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
